﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace XNAControls
{
    public class InputBox : Panel
    {
        public delegate void Accept(string Text);

        public event Accept TextAccepted;

        private string text;

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        public float BorderSize { get; set; }
        public Color ForeColor { get; set; }

        public SpriteFont Font { get; set; }

        public InputBox()
            : base()
        {
            BorderSize = 0;
            text = "";
            ForeColor = Color.White;
            Visible = false;
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            base.Draw(spriteBatch);
            if (Visible)
            {
                if (Font == null)
                {
                    throw new NullReferenceException("No font set");
                }

                int begInd = -1;
                string displayedText;
                do
                {
                    ++begInd;
                    displayedText = text.Substring(begInd);
                } while (Font.MeasureString("   " + displayedText).X > Size.X - 2 * BorderSize);

                spriteBatch.DrawString(Font, "   " + displayedText,
                                       new Vector2(Position.X + BorderSize, Position.Y + BorderSize), ForeColor);
            }
        }

        public void HandleInput(IEnumerable<Keys> keys)
        {
            foreach (Keys key in keys)
            {
                if (key == Keys.Enter)
                {
                    if (text.Length > 0 && TextAccepted != null)
                    {
                        TextAccepted.Invoke(text + "\n");
                        text = "";
                    }
                }
                else if (key == Keys.Back)
                {
                    if (text.Length > 0)
                    {
                        text = text.Remove(text.Length - 1);
                    }
                }
                else if (key == Keys.OemTilde)
                {

                }
                else if(key == Keys.OemPeriod)
                {
                    text += '.';
                }
                else
                {
                    int k = (int)key;
                    if (k >= 32 && k <= 126)
                    {
                        if (k >= 65 && k <= 90 && !keys.Contains(Keys.LeftShift) && !keys.Contains(Keys.RightShift))
                        {
                            k += 32;
                        }
                        text += (char)k;
                    }
                }
            }
        }
    }
}
